package org.mineground.commands.player.admin;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.mineground.Main;
import org.mineground.PermissionNodes;
import org.mineground.player.MinegroundPlayer;

/**
 * @name Invsee.java
 * @author Daniel Koenen (2012)
 */
public class InvSee implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] arguments) throws CommandException {
	Player player = (Player) sender;
        MinegroundPlayer playerInstance = Main.getInstance().getPlayer(player);

	if (!player.hasPermission(PermissionNodes.PERMISSION_INVSEE_COMMAND)) {
            return true;
        }

	if (arguments.length == 0 && playerInstance.getBackupInventory() == null) {
	    player.sendMessage(ChatColor.RED + "* Usage: '/invsee <player>'");
	    return true;
	}
        
        else if (playerInstance.getBackupInventory() != null) {
            player.getInventory().clear();
            player.getInventory().setContents(playerInstance.getBackupInventory());
            
            player.sendMessage(ChatColor.DARK_GREEN + "Your inventory has been restored.");
            playerInstance.setBackupInventory(null);
            return true;
        }
        
        Player invSeePlayer = Main.getInstance().getServer().getPlayer(arguments[0]);
        
        if (invSeePlayer == null || invSeePlayer == player) {
            player.sendMessage(ChatColor.RED + "* Error: Invalid player.");
            return true;
        }
        
        playerInstance.setBackupInventory(player.getInventory().getContents());
        
        player.getInventory().clear();
        player.getInventory().setContents(invSeePlayer.getInventory().getContents());
        player.sendMessage(ChatColor.DARK_GREEN + "You are now viewing " + invSeePlayer.getName() + "'s inventory.");
        player.sendMessage(ChatColor.DARK_GREEN + "Use '/invsee' again to restore your inventory.");
        return true;
    }
}
